package Linux五种IO模型;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author coderFu
 * @create 2022/3/6
 *
 * 感受AIO的力量 ！！！
 * 异步IO
 */
public class AIOServer {


    public void startListen(int port) throws InterruptedException{

        try{
            AsynchronousServerSocketChannel assc = AsynchronousServerSocketChannel.open();
            // 绑定端口
            assc.bind(new InetSocketAddress(port));
            assc.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

                @Override
                public void completed(AsynchronousSocketChannel result, Void attachment) {
                    // 收到连接后，应该调用accept方法等待新的连接进来
                    assc.accept(null,this);

                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    result.read(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                        @Override
                        public void completed(Integer result2, ByteBuffer attachment) {
                            if (result2 > 0) {
                                attachment.flip();
                                System.out.println(new String(attachment.array()).trim());
                            } else {
                                try {
                                    result.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                                System.out.println("read error");
                                exc.printStackTrace();
                        }
                    });

                }

                @Override
                public void failed(Throwable exc, Void attachment) {
                    System.out.println("accept error");
                    exc.printStackTrace();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true){
            Thread.sleep(1000);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        AIOServer aioServer = new AIOServer();
        aioServer.startListen(3214);
    }
}


